package com.atguigu.gulimail.cart.interceptor;


import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimail.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> userInfoToThreadLocal=new ThreadLocal<>();

    /**
     * 目标方法之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoTo userInfoTo=new UserInfoTo();//用来存储用户的信息{未登录： cookie存储，登录： session存储}

        //通过session来尝试获取用户登录信息；
        HttpSession session=request.getSession();
        MemberResponseVo member=(MemberResponseVo)session.getAttribute(AuthServerConstant.LOGIN_USER);

        //等于null说明没登录
        if(member!=null){
            userInfoTo.setUserId((member.getId()));
        }

        //查看是否有临时用户key
        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            for (Cookie cookie:cookies){
                //查看请求是否携带user-key的Cookie 未登录者的标识
                String name=cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setFlag(true);
                }
            }
        }


        //如果没有临时用户
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            //给用户分配一个临时用户
            String userKey= UUID.randomUUID().toString();
            userInfoTo.setUserKey(userKey);
        }

        //然后将UserInfo存储到ThreadLocal里面,然后将信息共享给Controller
        userInfoToThreadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后,不论是否登录，为一个用户分配临时用户唯一Cookie
     * 将临时用户的购物车数据存储到数据库
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

        //如果当前会话没有user-key临时用户这个Cookie,就在业务执行之后设置一个cookie
        UserInfoTo userInfoTo = userInfoToThreadLocal.get();
        if(!userInfoTo.isFlag()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoToThreadLocal.get().getUserKey());
            cookie.setDomain("gulimail.com");//设置Cookie的作用域,为整个gulimail.com
            cookie.setMaxAge(60*60*24*30);//设置Cookie的过期时间为30day
            response.addCookie(cookie);
        }

    }


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }

}
